package pers.xiaojun.boot.web.config;

import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import pers.xiaojun.boot.common.constants.WebFilterOrderConstants;
import pers.xiaojun.boot.web.core.annotation.AdminApi;
import pers.xiaojun.boot.web.core.annotation.AppApi;
import pers.xiaojun.boot.web.config.properties.WebProperties;

/**
 * MVC 配置
 *
 * @author xiaojun
 * @since 2025-10-04
 */
@AutoConfiguration
@EnableConfigurationProperties(WebProperties.class)
@RequiredArgsConstructor
public class WebAutoConfiguration implements WebMvcConfigurer {

    private final WebProperties webProperties;

    /**
     * API 路径匹配配置
     *
     * @param configurer 路径匹配配置
     */
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.addPathPrefix(webProperties.getAdminApiPrefix(), c -> c.isAnnotationPresent(AdminApi.class));
        configurer.addPathPrefix(webProperties.getAppApiPrefix(), c -> c.isAnnotationPresent(AppApi.class));
        configurer.addPathPrefix(webProperties.getApiPrefix(), c -> c.isAnnotationPresent(RestController.class));
    }

    /**
     * 配置跨域
     */
    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilterBean() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOriginPattern("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);

        FilterRegistrationBean<CorsFilter> registrationBean = new FilterRegistrationBean<>(new CorsFilter(source));
        registrationBean.setOrder(WebFilterOrderConstants.CORS_FILTER);
        return registrationBean;
    }

}
